/**
\file   mididump.c
\brief  Example using uC-MIDI Library.
        This example reads MIDI stream from standard input, parses it and
        dumps MIDI messages to the console in hex format.

Copyright (c) 2013 Gene Kozin <gkozin(at)gmail.com>

This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option)
any later version.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
more details.

You should have received a copy of the GNU General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
**/

#include <stdio.h>
#include <ucmidi.h>

/*
MIDI dispatch table. Here we just use library functions that will
eventually call our own midi_send().
*/
static midi_callback_t midi_cb = {
    send_note_on,               // note_on()
    send_note_off,              // note_off()
    send_key_pressure,          // key_pressure()
    send_control_change,        // control_change()
    send_program_change,        // program_change()
    send_chan_pressure,         // chan_pressure()
    send_pitch_bend,            // pitch_bend()
    send_sysex,                 // sysex()
    send_time_code,             // time_code()
    send_song_position,         // song_position()
    send_song_select,           // song_select()
    send_tune_request,          // tune_request()
    send_clock,                 // clock()
    send_start,                 // start()
    send_continue,              // cont()
    send_stop,                  // stop()
    send_active_sense,          // active_sense()
    send_reset,                 // reset()
};

/**
\brief  Application entry point.
**/
int main(int argc, char* argv[])
{
    printf("MIDI Dump Example. Using uC-MIDI Library Version %d.%d\n",
            UCMIDI_VERSION_MAJOR, UCMIDI_VERSION_MINOR);

    /* initialize MIDI parser */
    ucmidi_init(&midi_cb);

    /* read MIDI stream from the stdin and parse it */
    for (;;) {
        int c = getchar();
        if (c == EOF) {
            if (ferror(stdin)) {
                perror("stdin read error");
                return 1;
            }

            break;
        }
        
        midi_parser(c);
    }

    return 0;
}

/**
\brief	Dumps MIDI data in ASCII Hex format to the standard output.
**/
int midi_send(BYTE const* msg, int len)
{
    int cnt;

    printf("MIDI: ");
    for (cnt = 0; len; len--, cnt++) {
        printf("%02X ", *msg++);

        if (cnt % 16 == 15 && len > 1) {
            printf("\n      ");
        }
    }
    printf("\n");

    return 0;
}
